package xyz.zcq.zcqrpc.protocol;

import io.vertx.core.buffer.Buffer;
import xyz.zcq.zcqrpc.serializer.Serializer;
import xyz.zcq.zcqrpc.serializer.SerializerFactory;

import java.io.IOException;

/**
 * 协议消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 编码
     *
     * @param protocolMessage 协议消息
     * @return 字节数组
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        Buffer buffer = Buffer.buffer();
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            return buffer;
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();

        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        ProtocolMessageSerializerEnum pms = ProtocolMessageSerializerEnum.getByKey(header.getSerializer());
        if (pms == null) {
            throw new RuntimeException("序列化协议不存在");
        }
        Serializer serializer = SerializerFactory.getInstance(pms.getValue());
        byte[] body = serializer.serialize(protocolMessage.getBody());
        buffer.appendInt(body.length);
        buffer.appendBytes(body);

        return buffer;
    }

}
